/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;

import bean.Contrat;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import bean.Reservation;
import bean.Facture;
import dao.exceptions.IllegalOrphanException;
import dao.exceptions.NonexistentEntityException;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

/**
 *
 * @author mezouari
 */
public class ContratJpaController implements Serializable {

    public ContratJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Contrat contrat) {
        if (contrat.getFactureList() == null) {
            contrat.setFactureList(new ArrayList<Facture>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Reservation idReservation = contrat.getIdReservation();
            if (idReservation != null) {
                idReservation = em.getReference(idReservation.getClass(), idReservation.getId());
                contrat.setIdReservation(idReservation);
            }
            List<Facture> attachedFactureList = new ArrayList<Facture>();
            for (Facture factureListFactureToAttach : contrat.getFactureList()) {
                factureListFactureToAttach = em.getReference(factureListFactureToAttach.getClass(), factureListFactureToAttach.getId());
                attachedFactureList.add(factureListFactureToAttach);
            }
            contrat.setFactureList(attachedFactureList);
            em.persist(contrat);
            if (idReservation != null) {
                idReservation.getContratList().add(contrat);
                idReservation = em.merge(idReservation);
            }
            for (Facture factureListFacture : contrat.getFactureList()) {
                Contrat oldIdReservationOfFactureListFacture = factureListFacture.getIdReservation();
                factureListFacture.setIdReservation(contrat);
                factureListFacture = em.merge(factureListFacture);
                if (oldIdReservationOfFactureListFacture != null) {
                    oldIdReservationOfFactureListFacture.getFactureList().remove(factureListFacture);
                    oldIdReservationOfFactureListFacture = em.merge(oldIdReservationOfFactureListFacture);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Contrat contrat) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Contrat persistentContrat = em.find(Contrat.class, contrat.getId());
            Reservation idReservationOld = persistentContrat.getIdReservation();
            Reservation idReservationNew = contrat.getIdReservation();
            List<Facture> factureListOld = persistentContrat.getFactureList();
            List<Facture> factureListNew = contrat.getFactureList();
            List<String> illegalOrphanMessages = null;
            for (Facture factureListOldFacture : factureListOld) {
                if (!factureListNew.contains(factureListOldFacture)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Facture " + factureListOldFacture + " since its idReservation field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (idReservationNew != null) {
                idReservationNew = em.getReference(idReservationNew.getClass(), idReservationNew.getId());
                contrat.setIdReservation(idReservationNew);
            }
            List<Facture> attachedFactureListNew = new ArrayList<Facture>();
            for (Facture factureListNewFactureToAttach : factureListNew) {
                factureListNewFactureToAttach = em.getReference(factureListNewFactureToAttach.getClass(), factureListNewFactureToAttach.getId());
                attachedFactureListNew.add(factureListNewFactureToAttach);
            }
            factureListNew = attachedFactureListNew;
            contrat.setFactureList(factureListNew);
            contrat = em.merge(contrat);
            if (idReservationOld != null && !idReservationOld.equals(idReservationNew)) {
                idReservationOld.getContratList().remove(contrat);
                idReservationOld = em.merge(idReservationOld);
            }
            if (idReservationNew != null && !idReservationNew.equals(idReservationOld)) {
                idReservationNew.getContratList().add(contrat);
                idReservationNew = em.merge(idReservationNew);
            }
            for (Facture factureListNewFacture : factureListNew) {
                if (!factureListOld.contains(factureListNewFacture)) {
                    Contrat oldIdReservationOfFactureListNewFacture = factureListNewFacture.getIdReservation();
                    factureListNewFacture.setIdReservation(contrat);
                    factureListNewFacture = em.merge(factureListNewFacture);
                    if (oldIdReservationOfFactureListNewFacture != null && !oldIdReservationOfFactureListNewFacture.equals(contrat)) {
                        oldIdReservationOfFactureListNewFacture.getFactureList().remove(factureListNewFacture);
                        oldIdReservationOfFactureListNewFacture = em.merge(oldIdReservationOfFactureListNewFacture);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = contrat.getId();
                if (findContrat(id) == null) {
                    throw new NonexistentEntityException("The contrat with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Contrat contrat;
            try {
                contrat = em.getReference(Contrat.class, id);
                contrat.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The contrat with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Facture> factureListOrphanCheck = contrat.getFactureList();
            for (Facture factureListOrphanCheckFacture : factureListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Contrat (" + contrat + ") cannot be destroyed since the Facture " + factureListOrphanCheckFacture + " in its factureList field has a non-nullable idReservation field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Reservation idReservation = contrat.getIdReservation();
            if (idReservation != null) {
                idReservation.getContratList().remove(contrat);
                idReservation = em.merge(idReservation);
            }
            em.remove(contrat);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Contrat> findContratEntities() {
        return findContratEntities(true, -1, -1);
    }

    public List<Contrat> findContratEntities(int maxResults, int firstResult) {
        return findContratEntities(false, maxResults, firstResult);
    }

    private List<Contrat> findContratEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Contrat.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Contrat findContrat(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Contrat.class, id);
        } finally {
            em.close();
        }
    }

    public int getContratCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Contrat> rt = cq.from(Contrat.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
